package util;

import java.util.*;
import java.sql.*;

public class ConnectionPoolManager
{

	final String  databaseUrl = PropertyMgr.getConValue("jdbcURL");
	final String userName = PropertyMgr.getConValue("user");
	final String password = PropertyMgr.getConValue("passwd");
	final int MAX_POOL_SIZE = Integer.parseInt(PropertyMgr.getConValue("noc"));

	static Vector<Connection> connectionPool = new Vector<Connection>();

	public ConnectionPoolManager()
	{
		initialize();
	}

	private ConnectionPoolManager(
		//String databaseName,
		String databaseUrl,
		String userName,
		String password
		)
	{
		//this.databaseUrl = databaseUrl;
		//this.userName = userName;
		//this.password = password;
		initialize();
	}

	private void initialize()
	{
		//Here we can initialize all the information that we need
		initializeConnectionPool();
	}

	private void initializeConnectionPool()
	{
		while(!checkIfConnectionPoolIsFull())
		{
			Logger.ln("Connection Pool is NOT full. Proceeding with adding new connections");
			//Adding new connection instance until the pool is full
			connectionPool.addElement(createNewConnectionForPool());
		}
		Logger.ln("Connection Pool is full.");
	}

	private synchronized boolean checkIfConnectionPoolIsFull()
	{

		//Check if the pool size
		if(connectionPool.size() < 5)
		{
			return false;
		}

		return true;
	}

	//Creating a connection
	private Connection createNewConnectionForPool()
	{
		Connection connection = null;

		try
		{
			Class.forName("oracle.jdbc.OracleDriver");
			connection = DriverManager.getConnection(databaseUrl, userName, password);
			Logger.ln("Connection: "+connection);
		}
		catch(SQLException sqle)
		{
			System.err.println("SQLException: "+sqle);
			return null;
		}
		catch(ClassNotFoundException cnfe)
		{
			System.err.println("ClassNotFoundException: "+cnfe);
			return null;
		}

		return connection;
	}

	public static synchronized Connection getConnectionFromPool()
	{
		Connection connection = null;

		//Check if there is a connection available. There are times when all the connections in the pool may be used up
		if(connectionPool.size() > 0)
		{
			connection = (Connection) connectionPool.firstElement();
			connectionPool.removeElementAt(0);
		}
		//Giving away the connection from the connection pool
		return connection;
	}

	public static synchronized void returnConnectionToPool(Connection connection)
	{
		//Adding the connection from the client back to the connection pool
		connectionPool.addElement(connection);
	}

}